import React, { Component } from 'react';
import {
    StyleSheet, TouchableOpacity, BackHandler, Platform, Alert,
    Text,
    View, Button, Image, WebView
} from 'react-native';
import { connect } from 'react-redux';
import HeaderBar from '../../common/headerBar';
import { Variable } from '../../variables';
import DeviceRn from '../../components/Tools/device';
import Toast, { DURATION } from 'react-native-easy-toast';

let DevWH = DeviceRn().getWidHig();
let WEBVIEW_REF = "webview";
let dsb = "#a9a9a9";
let DEFAULT_URL = "https://www.baidu.com"
class WebScreen extends Component {
    static navigationOptions = ({ navigation, screenProps }) => (
        {
            header: null
        });
    constructor(props) {
        super(props);
        this.state = {
            url: DEFAULT_URL,
            //status: 'No Page Loaded',
            backButtonEnabled: false,
            forwardButtonEnabled: false,
            loading: true,
            scalesPageToFit: false,
        };
        this.index = 0;
        this.timers = "";
        Platform.OS === 'android' ? BackHandler.addEventListener('hardwareBackPress', this.androidBack) : null;
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.androidBack);
    }

    componentWillReceiveProps(nextProps) {
        this.netInfo = nextProps.status;
    }

    onNavigationStateChange = (navState) => {
        this.setState({
            backButtonEnabled: navState.canGoBack,
            forwardButtonEnabled: navState.canGoForward,
            url: navState.url,
            loading: navState.loading,
        });
    };

    androidBack = () => {
        if (!this.state.backButtonEnabled) {
            let timer = new Date().getTime();
            if (this.index == 0) {
                this.refs.toast.show('再按一次退出应用');
                this.timers = new Date().getTime();
                this.index++;
            } else {
                (timer - this.timers) / 1000 < 2.5 ? BackHandler.exitApp() : this.index = 0, this.timers = "";
            }
            return true;
        } else {
            this.index = 0;
            this.goBack();
            return true;
        }
    }

    goHome = () => {
        this.index = 0;
        let scriptGo = "window.history.go(-(window.history.length-1))";
        this.refs[WEBVIEW_REF].injectJavaScript(scriptGo);
    }

    goBack = () => {
        this.index = 0;
        this.refs[WEBVIEW_REF].goBack();
    };

    goForward = () => {
        this.index = 0;
        this.refs[WEBVIEW_REF].goForward();
    };

    reload = () => {
        this.index = 0;
        this.refs[WEBVIEW_REF].reload();
    };


    renderTools() {
        return (
            <View style={[styles.addressBarRow]}>
                <TouchableOpacity onPress={this.goHome}>
                    <View style={styles.fc}>
                        <Image style={styles.rtimg} source={require('../../assets/images/zy.png')} />
                        <Text style={styles.fctxt}>主页</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity onPress={this.reload}>
                    <View style={styles.fc}>
                        <Image style={styles.rtimg} source={require('../../assets/images/sx.png')} />
                        <Text style={styles.fctxt}>刷新</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity
                    disabled={this.state.backButtonEnabled ? false : true}
                    onPress={this.goBack}>
                    <View style={styles.fc}>
                        <Image style={[styles.rtimg, !this.state.backButtonEnabled ? { tintColor: dsb } : null]} source={require('../../assets/images/ht.png')} />
                        <Text style={[styles.fctxt, !this.state.backButtonEnabled ? { color: dsb } : null]}>后退</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity
                    disabled={this.state.forwardButtonEnabled ? false : true}
                    onPress={this.goForward}
                >
                    <View style={styles.fc}>
                        <Image style={[styles.rtimg, !this.state.forwardButtonEnabled ? { tintColor: dsb } : null]} source={require('../../assets/images/qj.png')} />
                        <Text style={[styles.fctxt, !this.state.forwardButtonEnabled ? { color: dsb } : null]}>前进</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }

    render() {
        return (
            <View style={styles.home}>
                <Toast ref="toast" position="bottom" />
                <WebView
                    ref={WEBVIEW_REF}
                    automaticallyAdjustContentInsets={false}
                    style={styles.webView}
                    source={{ uri: this.props.screenProps.url }}
                    javaScriptEnabled={true}
                    domStorageEnabled={true}
                    decelerationRate="normal"
                    onNavigationStateChange={this.onNavigationStateChange}
                    startInLoadingState={true}
                    scalesPageToFit={this.state.scalesPageToFit}
                />
                {this.renderTools()}
            </View>
        );
    }
}
mapStoreState = (store) => ({
    status: store.netInfo.status,
});
export default connect(mapStoreState)(WebScreen);

const styles = StyleSheet.create({
    home: {
        flex: 1,
        //justifyContent: 'center',
        alignItems: 'flex-start',
        backgroundColor: '#fff',
        marginVertical: 0,
    },
    addressBarRow: {
        flex: 0,
        width: DevWH.sW,
        position: 'absolute',
        height: 46,
        flexDirection: 'row',
        justifyContent: 'space-around',
        alignItems: 'center',
        backgroundColor: '#fff',
        bottom: 0,
        borderTopColor: '#e0e0e0',
        borderTopWidth: 1,
        padding: 4
    },
    fc: {
        flex: 0,
        justifyContent: 'center',
        alignItems: 'center',
    },
    fctxt: {
        fontSize: 10,
        fontWeight: '500',

    },
    rtimg: {
        width: 22, height: 22, resizeMode: 'contain'
    },
    webView: {
        flex: 1,
        width: DevWH.sW,
        bottom: 46
    },
});